local skynet = require "skynet"
local socket = require "socket"
local cluster = require "cluster"
local snax = require "snax"
local CMD = require "center_proto"
local WATCHDOG

local client_fd
local client_addr  = nil
local dataser      = nil
local addr         = nil
local __gameid     = nil
local __tableid    = nil
local __type       = nil
local proxyser     = nil
local refresh_time = 0

local function send_package(fd, pack)
	local package = string.pack(">s2", pack)
	socket.write(fd, package)
end


local function error_toClose()
    skynet.call(WATCHDOG, "lua", "close", client_fd)
end


local function request(smsg, sz)

    if sz < 4 then
        skynet.error("error close fd find  non-standard packet sz:"..sz)
        error_toClose()
        return nil
    end

     
    local mcmd,scmd = string.unpack(">I2>I2", smsg, 1)   
    
    --skynet.error("<data agent>中心服收到协议",mcmd,scmd)
    
    
    if mcmd==CMD.Main_Center_module then
        if scmd == CMD.Sub_ModuleToCenter_CheckNet then
            return string.pack(">I2>I2",mcmd, scmd)
        else 
            --local body = centerserver.req.request_module(scmd,sz,smsg,addr)
            skynet.error("游戏服务器to数据服",mcmd,scmd)
            local body = cluster.call("master", centerserver,"request_module", scmd,sz,smsg,addr)
        end
    elseif mcmd == CMD.Main_hall_module then 
        skynet.error("游戏服务器to大厅 ",mcmd,scmd)
        hallserver.req.request_hall( {cmd = scmd,msg = smsg,addr = addr} )       
    elseif mcmd == CMD.Main_match_module then 
        skynet.error("游戏服务器to协调服务器  ",mcmd, scmd)
        matchser.post.recv_from_game(scmd, smsg)
    end
end


skynet.register_protocol {
	name = "client",
	id = skynet.PTYPE_CLIENT,
    unpack = function(msg,sz) 
        return  skynet.tostring(msg,sz), sz  
    end,
	dispatch = function (_, _, smsg, sz)
		local ok, result  = pcall(request, smsg, sz)
		if ok then
			if result then
				send_package(client_fd, result)
			end
		else
			skynet.error(result)
		end
	end
}

function CMD.start(conf)
	local fd = conf.client
	local gate = conf.gate
	WATCHDOG = conf.watchdog
    local s, e = string.find(conf.clientaddr, ":")
    client_addr = string.sub(conf.clientaddr, 1, s-1) 

    skynet.error("CMD.start ip="..client_addr)

	client_fd = fd
	skynet.call(gate, "lua", "forward", fd)

    send_package(client_fd,string.pack(">I2>I2",215,client_fd))
  
end

function CMD.ToGame(msg)
   skynet.error("[Center_agent CMD.ToGame] client_fd :"..client_fd.."  tableid:"..__tableid.." send packet len "..string.len(msg))
   local a,b = string.unpack(">I2>I2",msg,1)
   skynet.error("[Center agent CMD.ToGame] 主码："..a.." 子码："..b)
   send_package(client_fd,msg)
end

function CMD.GetFefreshTime(addr)
    skynet.send(addr,"lua", "GetFefreshTime", refresh_time)
end

function CMD.set_tableid(msg)
    __gameid  = msg.gid
    __tableid = msg.tblid
    __type    = msg.ttype
    skynet.error("CMD.set_tableid gameid=",__gameid," tableid=",__tableid," type=",__type)
end

function CMD.disconnect()
    skynet.error("CMD.disconnect addr=",addr," tableid=",__tableid," type=",__type)
    --centerserver.req.request_module( CMD.Sub_ModuleToCenter_GSUnReg,0,{gid=__gameid,tid=__tableid,type=__type},addr )
    cluster.call("master", centerserver,"request_module", CMD.Sub_ModuleToCenter_GSUnReg,0,{gid=__gameid,tid=__tableid,type=__type},addr)
    skynet.exit()
end

skynet.start(function()
    
	skynet.dispatch("lua", function(_,_, command, ...)
		local f = CMD[command]
		skynet.ret(skynet.pack(f(...)))
	end)
    centerserver = cluster.query("master", "centerser")  
    hallserver = cluster.snax("center", "hallser") 
    matchser = cluster.snax("center", "matchser") 
    addr = skynet.self()
    skynet.error("agnet start ***********",addr)
    math.randomseed(os.time())
end)
